package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.RandomUtils;
import com.atguigu.srb.sms.Service.SmsService;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.utils.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/api/sms")
@Api(tags="短信管理")
@RestController
//@CrossOrigin
@Slf4j
public class ApiSmsController {
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    CoreUserInfoClient coreUserInfoClient;

     @Resource
     SmsService smsService;

    @GetMapping("/send/{mobile}")
    @ApiOperation("发送短信验证码")
    public R send(@ApiParam(value = "短信验证码",required = true)
                  @PathVariable("mobile") String mobile){
        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //读取短信模板
        String TemplateCode=   SmsProperties.TEMPLATE_CODE;
        //短信参数
        String sixBitRandom = RandomUtils.getSixBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code",sixBitRandom);
        //判断手机号是否已经存在
         Boolean isExist  = coreUserInfoClient.checkMobile(mobile);
         Assert.isTrue(isExist==false,ResponseEnum.MOBILE_EXIST_ERROR);
        String send = smsService.send(mobile, TemplateCode, map);
        redisTemplate.opsForValue().set("yanzhenma",sixBitRandom);
       return R.ok().message("发送短信成功");
    }


}
